package com.boot.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
public class TestController {
//    @ApolloConfig
//    private Config apolloConfig;

    private RefreshScope refreshScope;

    @Autowired
    private KafkaTemplate<String, String> template;
    private Random random = new Random();

//    @ApolloConfigChangeListener
//    private void someChangeHandler(ConfigChangeEvent changeEvent) {
//        if (changeEvent.isChanged("request.timeout")) {
//            //时间监听
//        }
//    }

//    @RequestMapping("demo/index")
//    public String index() {
//        System.out.println(this.config.getDefaultKeySerde());
//        System.out.println("serde=" + this.serde);
//        return this.jdbcUrl;
//    }

    private List<String> keys = new ArrayList<>();
    private int[] status = {0, 1, 2};

    @PostConstruct
    public void init() {
        this.keys.addAll(Arrays.asList(new String[]{"key-0", "key-1", "key-2", "key-3", "key-4", "key-5", "key-6", "key-7", "key-08", "key-9"}));
    }

    @RequestMapping("send")
    public String send() {
        Map<String, Object> map = new HashMap<>();
        map.put("key", this.keys.get(new Random().nextInt(this.keys.size())));
        //map.put("key", "key-0");
        map.put("fee", RandomUtils.nextFloat());
        map.put("time", this.random.nextInt(500));//s
        map.put("status", this.status[RandomUtils.nextInt(3)]);
        map.put("creatTime", System.currentTimeMillis());
        String key = UUID.randomUUID().toString();
        this.template.send(new ProducerRecord<>("api-charge-stream", key, JSONObject.toJSONString(map)));
        return "ok";
    }

}
